<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket通讯</title>
</head>
<script src="https://cdn.staticfile.org/jquery/2.0.0/jquery.min.js"></script>
<script>
    let socket;
    function openSocket() {
        const socketUrl = "ws://localhost:9005/api/pushMessage/" + $("#userId").val();
        console.log(socketUrl);
        if(socket!=null){
            socket.close();
            socket=null;
        }
        // 创建 websocket
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function() {
            console.log("websocket已打开");
        };
        //获得消息事件
        socket.onmessage = function(msg) {
            console.log(msg.data);
            //发现消息进入,开始处理前端触发逻辑
        };
        //关闭事件
        socket.onclose = function() {
            console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function(e) {
            console.log(e);
            console.log("websocket发生了错误");
        }
    }
    function sendMessage() {
        socket.send('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
        console.log('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
    }
</script>
<body>
<p>【socket开启者的ID信息】：<div><input id="userId" name="userId" type="text" value="10"></div>
<p>【客户端向服务器发送的内容】：<div><input id="toUserId" name="toUserId" type="text" value="20">
    <input id="contentText" name="contentText" type="text" value="hello websocket"></div>
<p>【操作】：<div><a onclick="openSocket()">开启socket</a></div>
<p>【操作】：<div><a onclick="sendMessage()">发送消息</a></div>
</body>

</html>
